package com.luoxiang.socialandroid.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaMetadataRetriever;
import android.os.Build;
import android.util.Log;

import com.blankj.utilcode.util.LogUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;

/**
 * @Description TODO
 * @systemUser Administrator
 * @Author lx
 * @Date 09-01-2022 周四 14:26
 */
public class BitmapUtils {
    /**
     * 通过网络url获取视频缩略图
     *
     * @param url 文件路径
     * @return Bitmap 缩略图
     */
    public static Bitmap getBitmapFormNetUrl(String url) {
        LogUtils.dTag("videoUrl",url);
        Bitmap bitmap = null;
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
            if (Build.VERSION.SDK_INT >= 14) {
                retriever.setDataSource(url, new HashMap<String, String>());
            } else {
                retriever.setDataSource(url);
            }
            bitmap = retriever.getFrameAtTime();
        } catch (RuntimeException ex) {
            // Assume this is a corrupt video file.
        } finally {
            try {
                retriever.release();
            } catch (RuntimeException ex) {
                // Ignore failures while cleaning up.
            }
        }
        return bitmap;
    }

    String Tag=getClass().getSimpleName();
    private static BitmapUtil instance = null;
    private MediaMetadataRetriever media = null;

    public static BitmapUtil getInstance() {
        if (instance == null) {
            instance = new BitmapUtil();
        }
        return instance;
    }

    public Bitmap getVideoBimap(String path) {
        if (this.media == null) {
            this.media = new MediaMetadataRetriever();
        }
        try{
            this.media.setDataSource(path);
            //获取指定位置指定宽高的缩略图
            //return this.media.getScaledFrameAtTime(-1, MediaMetadataRetriever.OPTION_CLOSEST, 400, 300);
            return this.media.getFrameAtTime();
        }catch (Exception ex){
        }
        return null;
    }

    public static byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 100, output);
        if (needRecycle) {
            bmp.recycle();
        }

        byte[] result = output.toByteArray();
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

}
